//
//  DetailViewController.m
//  Iderun
//
//  Created by Zhou, Shaolin on 6/10/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DetailViewController.h"
#import "JSON.h"
#import "AppDelegate.h"
#import "ImageScrollView.h"
#import "ShenHeViewController.h"
#import "XmlReader.h"
#import "MBProgressHUD.h"
#import "CustomNavigationController.h"
#define FONTSIZE 12

@implementation DetailViewController

@synthesize itemDictory;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
            self.edgesForExtendedLayout = UIRectEdgeNone;
        }

        self.title = @"单据查看";

    }
    return self;
}

#pragma mark - View lifecycle

- (void)viewDidLoad{
    [super viewDidLoad];
    UIBarButtonItem *leftButton=[[UIBarButtonItem alloc] initWithCustomView:[self customButtom:100 withFrame:CGRectMake(10, 0, 49, 29) action:@selector(popBack:) normalImage:@"back_button.png" lightedImage:@"back_button.png" title:@""]];
    leftButton.style = UIBarButtonItemStylePlain;
    self.navigationItem.leftBarButtonItem=leftButton;
    [leftButton release];
    [self  loadImageFromURL];
}

-(void) addTopMenu{
    UIView *menuview =[[UIView  alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    menuview.tag=159;
    menuview.backgroundColor=[UIColor  clearColor];
    UIButton *button1=[self  customButtom:160 withFrame:CGRectMake(0, 5, 160, 30) action:@selector(touchDownAction:) normalImage:@"danju.png" lightedImage:@"danju_over.png" title:@""];
    UIButton *button2=[self  customButtom:161 withFrame:CGRectMake(160, 5, 160, 30) action:@selector(touchDownAction:) normalImage:@"liucheng.png" lightedImage:@"liucheng_over.png" title:@""];
    [menuview addSubview:button1];
    [menuview addSubview:button2];
    [self.view  addSubview:menuview];
    [menuview release];
    
    CGRect rect=[[UIScreen mainScreen] bounds];
    rect.size.height=rect.size.height-[UIApplication sharedApplication].statusBarFrame.size.height-self.navigationController.navigationBar.frame.size.height;
    rect.origin.y=40;
    UIView *secondView=[[UIView alloc] initWithFrame:rect];
    secondView.tag=181;
    secondView.hidden=YES;
    secondView.backgroundColor=[UIColor whiteColor];
    [self.view  addSubview:secondView];
    [secondView release];
}

-(void) showShenheButton{
    UISegmentedControl *segmentedControl=[[UISegmentedControl alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 80.0f, 30.0f) ];
    [segmentedControl insertSegmentWithTitle:@"同意" atIndex:0 animated:YES];
    [segmentedControl insertSegmentWithTitle:@"驳回" atIndex:1 animated:YES];
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
    
    /*[segmentedControl insertSegmentWithImage:[UIImage  imageNamed:@"Icon.png"] atIndex:0 animated:YES];
     [segmentedControl insertSegmentWithImage:[UIImage  imageNamed:@"Icon.png"] atIndex:1 animated:YES];
     segmentedControl.segmentedControlStyle = UISegmentedControlSegmentAlone;*/
    segmentedControl.momentary = YES;
    segmentedControl.multipleTouchEnabled=NO;
    [segmentedControl addTarget:self action:@selector(Selectbutton:) forControlEvents:UIControlEventValueChanged];
    UIBarButtonItem *segButton = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
    [segmentedControl release];
    self.navigationItem.rightBarButtonItem = segButton;
    [segButton release];
    
}


#pragma mark - Managing the detail item

-(void) loadImageFromURL{
    for (UIView  *view in self.view.subviews) {
        [view removeFromSuperview];
    }
    AppDelegate *appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    [MBProgressHUD  showHUDAddedTo:appdelegate.tabbar.view animated:NO];
    [self  performSelectorInBackground:@selector(downLoadImageData) withObject:nil];
}

-(void) downLoadImageData{
    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
    NSString *orderId=[[self.itemDictory objectForKey:@"单号"] objectForKey:@"text"];
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults]; 
    
    NSError *error;
        NSDictionary *resultData=[XmlReader dictionaryForXMLString:[userdefault  objectForKey:@"sysParams"] error:&error];
    NSArray *param=[[resultData objectForKey:@"sysParams"] objectForKey:@"string"];
    if ([param count]>0) {
        NSString *htdc=[[[param objectAtIndex:[param count]-1] objectForKey:@"text"] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        NSString *baseUrl=[userdefault objectForKey:@"kServiceURL"];
        NSString *url;
        if([baseUrl hasSuffix:@"/"]){
          url=[NSString stringWithFormat:@"%@%@/BillJpg/%@.jpg",baseUrl,htdc,orderId];
        }else{
          url=[NSString stringWithFormat:@"%@/%@/BillJpg/%@.jpg",baseUrl,htdc,orderId];
        }
        NSData *data=[NSData  dataWithContentsOfURL:[NSURL URLWithString:url]];
        [self performSelectorOnMainThread:@selector(loadImageForUI:) withObject:data waitUntilDone:NO];
    }else {
        [self performSelectorOnMainThread:@selector(loadImageForUI:) withObject:nil waitUntilDone:NO];
    }
        [pool  release];
}

-(void) loadImageForUI:(NSData*) data{
    if (data==nil) {
        NSString* okTitle = @"提醒";
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"图片路径配置出错" delegate:nil cancelButtonTitle:okTitle otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 40, 320, 376)];
    imageView.image=[UIImage imageWithData:data];
    //[imageView setImageWithURL:[NSURL URLWithString:url] refreshCache:NO];
    imageView.contentMode=UIViewContentModeScaleAspectFit;
    ImageScrollView *imageScrollView=[[ImageScrollView alloc] initWithFrame:self.view.bounds imageView:imageView];
    imageScrollView.tag=180;
    //imageScrollView.backgroundColor=[UIColor  blueColor];
    [self.view addSubview:imageScrollView];
    [imageScrollView release];
    [imageView release];
    AppDelegate *appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    [MBProgressHUD  hideHUDForView:appdelegate.tabbar.view animated:NO];
    [self addTopMenu];
    [self dimssAllButtonsExcept:[self.view viewWithTag:160]];
    if (urlRequest == nil) {
        urlRequest = [[UrlRequest alloc] initWithDelegate:self requestSelector:@selector(parseReceivedData:) errorSelector:@selector(errorCallback)];
    }
    [urlRequest  requestToLiuChengShePi:[[self.itemDictory objectForKey:@"单号"] objectForKey:@"text"]];
}

-(IBAction)popBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void) Selectbutton:(UISegmentedControl*) sender{
    ShenHeViewController *shenhe=[[ShenHeViewController alloc] initWithNibName:nil bundle:nil];
    if (sender.selectedSegmentIndex==0) {
        shenhe.flag=0;
    }else{
        shenhe.flag=1;
    }
    [shenhe initContent];
    AppDelegate *appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
     shenhe.itemDictory=self.itemDictory;
    CustomNavigationController *nav=[[CustomNavigationController alloc] initWithRootViewController:shenhe];
    [appdelegate.tabbar  presentModalViewController:nav animated:NO];
    [shenhe  release];
    [nav  release];
    
}

- (IBAction)touchDownAction:(id)  sender{ 
    [self dimssAllButtonsExcept:sender];
    UIButton *button=(UIButton*)sender;
     UIView * secondView=[self.view  viewWithTag:181];
    if (button.tag==160) {
        secondView.hidden=YES;
        [self loadImageFromURL];
    
    }else if(button.tag==161){
        secondView.hidden=NO;
    } 
}

- (IBAction)dimssAllButtonsExcept:(id)  sender{ 
    UIView *topMenu=[self.view  viewWithTag:159];
    for (UIView* view in topMenu.subviews){   
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *button=(UIButton *) view;
            if (button == sender){
                //button.backgroundColor=[UIColor blueColor];
                button.selected = YES;
                button.highlighted = button.selected ? NO : YES;
            }else{
                //button.backgroundColor=[UIColor clearColor];
                button.selected = NO;
                button.highlighted = NO;
            }
        }
    } 
   
}

-(void)parseReceivedData:(id)data{
    AppDelegate *appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    if (data==nil||[data isEqualToString:@""]) {
        NSLog(@"detail receivedString=%@",@"空");
        [MBProgressHUD  hideHUDForView:appdelegate.tabbar.view animated:NO];
        return;
    }
     NSError *error;
    NSDictionary *resultData=[XmlReader dictionaryForXMLString:data error:&error];
     NSArray *array=[[[[[[[resultData  objectForKey:@"soap:Envelope"] objectForKey:@"soap:Body"] objectForKey:@"GetDataSetSqlResponse"] objectForKey:@"GetDataSetSqlResult"] objectForKey:@"diffgr:diffgram"] objectForKey:@"NewDataSet"] objectForKey:@"Table"];
    
    UIView *secView=[self.view  viewWithTag:181];
    int j=0;
    NSMutableSet *set=[NSMutableSet set];
    for (int i=0;i<[array count];i++) {
       //NSLog(@"%@",[[array  objectAtIndex:i] JSONRepresentation]);
        NSString *personStr=[[[array  objectAtIndex:i] objectForKey:@"审批人"] objectForKey:@"text"];
        NSString *yijianStr=[[[array  objectAtIndex:i] objectForKey:@"审批意见"] objectForKey:@"text"];
        NSString *zhiwuStr=[[[array  objectAtIndex:i] objectForKey:@"审批人职务"] objectForKey:@"text"];
        
        NSString *updateDateStr=[[[array  objectAtIndex:i]  objectForKey:@"审批时间"] objectForKey:@"text"];
        NSString *shijianStr=[[updateDateStr  componentsSeparatedByString:@"T"]objectAtIndex:0];
        //NSLog(@"%@--%@--%@--%@",personStr,yijianStr,zhiwuStr,shijianStr);
        if (personStr==nil||[@"" isEqualToString:personStr]) {
            continue;
        }else {
            if ([set containsObject:personStr]) {
                continue;
            }else{
                [set addObject:personStr]; 
                j=j+1;
            }
        }  
        
        
        UIView  *view=[[UIView alloc] initWithFrame:CGRectMake(0, 50*(j-1), 320, 55)];
        UILabel *person=[[UILabel alloc] initWithFrame:CGRectMake(10, 0, 110, 20)];
         person.font=[UIFont  fontWithName:@"STHeitiTC-Medium" size:12];
        person.textAlignment=UITextAlignmentRight;
        person.text=personStr;
        person.backgroundColor=[UIColor  clearColor];
        [view  addSubview:person];
        [person  release];
       
        UILabel *yijian=[[UILabel alloc] initWithFrame:CGRectMake(130, 0, 180, 20)];
        yijian.textAlignment=UITextAlignmentLeft;
        yijian.font=[UIFont  fontWithName:@"STHeitiTC-Medium" size:12];
        yijian.text=yijianStr;
        yijian.backgroundColor=[UIColor  clearColor];
        [view  addSubview:yijian];
        [yijian  release];
        
        UILabel *zhiwu=[[UILabel alloc] initWithFrame:CGRectMake(10, 20, 110, 20)];
        zhiwu.textAlignment=UITextAlignmentRight;
         zhiwu.font=[UIFont  fontWithName:@"STHeitiTC-Medium" size:12];
        zhiwu.text=zhiwuStr;
        zhiwu.backgroundColor=[UIColor  clearColor];
        [view  addSubview:zhiwu];
        [zhiwu  release];
        
        UILabel *shijian=[[UILabel alloc] initWithFrame:CGRectMake(130, 20, 180, 20)];
         shijian.font=[UIFont  fontWithName:@"STHeitiTC-Medium" size:12];
        shijian.textAlignment=UITextAlignmentLeft;
        shijian.text=shijianStr;
        shijian.backgroundColor=[UIColor  clearColor];
        [view  addSubview:shijian];
        [shijian  release];
        if (i<[array count]-1) {
            UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 42, 320, 1)];
            imageView.image=[UIImage imageNamed:@"split.png"];
            [view addSubview:imageView];
            [imageView release];
        }
    [view  setBackgroundColor:[UIColor  clearColor]];
    [secView  addSubview:view];
    [view  release];
    }
     
}

-(void)errorCallback{
}

- (void)viewDidUnload{
    [super viewDidUnload];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated{
	[super viewDidDisappear:animated];
}





- (UIButton*) customButtom:(NSUInteger)numberOfTag withFrame:(CGRect)frame action:(SEL)action normalImage:(NSString*)normalImage lightedImage:(NSString*)lightedImage  title:(NSString *)title{
    UIButton* button;
    if (title==nil||[@"" isEqualToString:title]) {
         button = [UIButton buttonWithType:UIButtonTypeCustom];
    }else {
         button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
         [button setTitle:title forState:UIControlStateNormal];
    }
    
    button.frame = frame;
    button.tag=numberOfTag;
    button.backgroundColor=[UIColor clearColor];
   
    if (![normalImage isEqualToString:@""]) {
        UIImage *normal_Image=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:normalImage ofType:nil]];
        [button setImage:normal_Image forState:UIControlStateNormal];
    }
    
    if (![lightedImage isEqualToString:@""]) {
        UIImage *lighted_Image=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:lightedImage ofType:nil]];
        [button setImage:lighted_Image forState:UIControlStateHighlighted];
        [button setImage:lighted_Image forState:UIControlStateSelected];
    }
    
    button.adjustsImageWhenHighlighted = NO;
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    return button;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation==UIDeviceOrientationPortrait);
}
- (BOOL)shouldAutorotate{
    return NO;
}
- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc{
    [itemDictory release];
    [urlRequest  release];
    [super dealloc];
}


							
@end
